package cn.yx.framework.log;

import cn.com.yx.ms.controller.MqController;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.util.DateUtil;
import com.alibaba.druid.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;

/**
 * Created by Administrator on 2017/3/11.
 */
public class MyLogger {
    private static final Logger logger = LoggerFactory.getLogger(MyLogger.class);

    private static String DEFAULT_ENCODE = "UTF-8";

    public MyLogger() {
    }

    public static void log(String path, String content) throws Exception {
        String nowTime = DateUtil.date2String(new Date(), "yyyy-MM-dd hh");
        saveFile(BaseConstant.getMyLogConfig().getLogpath() + "/"
                        + path + "/"
                        + nowTime + ".log",
                "[" + DateUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "]"
                        + content + "\r\n");
    }

    private static void saveFile(String path, String content) throws Exception {
        saveFile(path, content, DEFAULT_ENCODE);
    }

    /**
     * 保存文件(文件不存在会自动创建).
     *
     * @param path     文件路径
     * @param content  文件内容
     * @param encoding 编码(UTF-8/gb2312/...)
     * @throws Exception
     */
    private static void saveFile(String path, String content, String encoding) throws Exception {
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bw = null;
        try {
            // 获得文件对象
            File f = new File(path);
            // 默认编码UTF-8
            encoding = (StringUtils.isEmpty(encoding)) ? DEFAULT_ENCODE : encoding;
            // 如果路径不存在,则创建
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            // 开始保存文件
            fileOutputStream = new FileOutputStream(path, true);
            bw = new BufferedOutputStream(fileOutputStream);
            bw.write(content.getBytes(encoding));
        } catch (Exception e) {
            logger.error("保存文件错误.path=" + path + ",content=" + content + ",encoding=" + encoding, e);
            //throw e;
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e1) {
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e1) {
                }
            }
        }
    }
}
